package com.mzj.saas.mservice.property.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.haixiaoke.saas.repository.pojo.ElectronicSigningContract;
import com.haixiaoke.saas.repository.service.IElectronicSigningContractService;
import com.mzj.saas.commons.ApiData;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.SQLUtils;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.util.StringUtils;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.community.repository.CommunityRepository;
import com.mzj.saas.mservice.community.service.AppCommunityService;
import com.mzj.saas.mservice.community.service.CommunityService;
import com.mzj.saas.mservice.department.entity.Department;
import com.mzj.saas.mservice.department.repository.DepartmentRepository;
import com.mzj.saas.mservice.eligible.entity.DepartmentEnterpriseTagRef;
import com.mzj.saas.mservice.eligible.entity.DepartmentHierarchy;
import com.mzj.saas.mservice.eligible.repository.DepartmentEnterpriseTagRefRepository;
import com.mzj.saas.mservice.eligible.repository.DepartmentHierarchyRepository;
import com.mzj.saas.mservice.house.entity.House;
import com.mzj.saas.mservice.house.repository.HouseRepository;
import com.mzj.saas.mservice.house.vo.MatchUserVO;
import com.mzj.saas.mservice.lock.Repository.SmartLockAuthRepository;
import com.mzj.saas.mservice.lock.Repository.SmartLockRepository;
import com.mzj.saas.mservice.lock.entity.SmartLock;
import com.mzj.saas.mservice.lock.entity.SmartLockAuth;
import com.mzj.saas.mservice.property.entity.CommunityHouseUser;
import com.mzj.saas.mservice.property.repository.CommunityHouseUserRepository;
import com.mzj.saas.mservice.property.vo.CommunityHouseUserVO;
import com.mzj.saas.mservice.property.vo.HouseUserVo;
import com.mzj.saas.mservice.property.vo.MatchUserHouseVO;
import com.mzj.saas.mservice.property.vo.PropertyCommunityHouseVO;
import com.mzj.saas.mservice.sys.utils.SqlUtils;
import com.mzj.saas.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PropertyCommunityHouseService {
    private static final Logger log = LoggerFactory.getLogger(PropertyCommunityHouseService.class);

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private AppCommunityService appCommunityService;
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private CommunityService communityService;
    @Autowired
    private SmartLockAuthRepository smartLockAuthRepository;
    @Autowired
    private CommunityHouseUserRepository communityHouseUserRepository;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private DepartmentEnterpriseTagRefRepository departmentEnterpriseTagRefRepository;
    @Autowired
    private HouseRepository houseRepository;
    @Autowired
    private CommunityRepository communityRepository;
    @Autowired
    private IElectronicSigningContractService electronicSigningContractService;

    public ResultBean<ApiData<PropertyCommunityHouseVO>> listBy(String accessToken, Integer determineType, String searchCondition,
                                                                String houseId, String communityId, Long buildId, Long unitId, String roomNumber, Integer floor,
                                                                String ownerName, String ownerMobile, Integer userCount, Integer pageNumber, Integer pageSize) {
        try {
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null) {
                return ResultBean.failedResultOfToken();
            }
            Long enterpriseId = token.getEnterpriseId();
            String phone = token.getPhone();
            log.info("用户列表查询, token={}", JSON.toJSONString(token));
            ApiData<PropertyCommunityHouseVO> apiData = new ApiData<>();

            List<Map<String, Object>> communityList = appCommunityService.findCommunity(accessToken).getResultData();

            String querySql = "SELECT sch.id,sch.residence_community_id AS communityId,sc.name AS communityName,sch.building_num as buildId ,scb.name AS buildName ,sch.unit as unitId,scbu.name AS unitName,\n" +
                    "sch.`floor`,sch.`room_number` AS roomNumber,sch.`house_property_id` AS housePropertyId,sch.`owner_name` as ownerName,sch.`owner_mobile` as ownerMobile, \n" +
                    "sch.`status`,sch.`operation_id` AS operationId,sch.create_time as createTime,sch.house_nature as houseNature,sch.org_id as orgId,pp.userCount,sch.housemate_id as housemateId,sch.match_type as matchType\n" +
                    "FROM saas_house sch LEFT JOIN saas_community sc ON sch.residence_community_id = sc.id \n" +
                    "LEFT JOIN saas_community_build scb ON sch.building_num = scb.id \n" +
                    "LEFT JOIN saas_community_build_unit scbu ON sch.unit = scbu.id \n" +
                    "LEFT JOIN saas_department d ON sch.org_id = d.id \n" +
                    "LEFT JOIN (\n" +
                    "SELECT houseId,SUM(userCount) AS userCount FROM (\n" +
                    "SELECT h.id AS houseId, COUNT(app.match_user_id) userCount \n" +
                    "FROM saas_house_eligible_apply app\n" +
                    "LEFT JOIN saas_house_match_user mu ON  mu.apply_id = app.id\n" +
                    "LEFT JOIN saas_house h ON h.id = mu.house_id   GROUP BY h.id \n" +
                    "UNION ALL\n" +
                    "SELECT h.id AS houseId, COUNT(ac.id) AS userCount \n" +
                    "FROM saas_house_eligible_apply_cohabit ac\n" +
                    "LEFT JOIN saas_house_eligible_apply app ON app.id = ac.apply_id\n" +
                    "LEFT JOIN saas_house_match_user mu ON  mu.apply_id = app.id\n" +
                    "LEFT JOIN saas_house h ON h.id = mu.house_id   GROUP BY h.id \n" +
                    "UNION ALL \n" +
                    "SELECT hu.community_house_id AS houseId, COUNT(id) AS userCount \n" +
                    "FROM saas_community_house_user hu where hu.status = 1 AND hu.type != 3 GROUP BY houseId ) p GROUP BY houseId \n" +
                    ") pp ON pp.houseId = sch.id where sch.status = 1 AND ";
            String countSql = "SELECT COUNT(*) FROM saas_house sch LEFT JOIN saas_community sc ON sch.residence_community_id = sc.id " +
                    "LEFT JOIN saas_community_build scb ON sch.building_num = scb.id " +
                    "LEFT JOIN saas_community_build_unit scbu ON sch.unit = scbu.id " +
                    "LEFT JOIN saas_department d ON sch.org_id = d.id \n" +
                    "LEFT JOIN (\n" +
                    "SELECT houseId,SUM(userCount) AS userCount FROM (\n" +
                    "SELECT h.id AS houseId, COUNT(app.match_user_id) userCount \n" +
                    "FROM saas_house_eligible_apply app\n" +
                    "LEFT JOIN saas_house_match_user mu ON  mu.apply_id = app.id\n" +
                    "LEFT JOIN saas_house h ON h.id = mu.house_id GROUP BY h.id \n" +
                    "UNION ALL\n" +
                    "SELECT h.id AS houseId, COUNT(ac.id) AS userCount \n" +
                    "FROM saas_house_eligible_apply_cohabit ac\n" +
                    "LEFT JOIN saas_house_eligible_apply app ON app.id = ac.apply_id\n" +
                    "LEFT JOIN saas_house_match_user mu ON  mu.apply_id = app.id\n" +
                    "LEFT JOIN saas_house h ON h.id = mu.house_id GROUP BY h.id \n" +
                    "UNION ALL \n" +
                    "SELECT hu.community_house_id AS houseId, COUNT(id) AS userCount \n" +
                    "FROM saas_community_house_user hu where hu.status = 1 AND hu.type != 3 GROUP BY houseId ) p GROUP BY houseId \n" +
                    ") pp ON pp.houseId = sch.id where sch.status = 1 AND ";

            Map<String, Object> params = new HashMap<>();
            if (determineType != null && determineType == 1) {
                params.put("limit", pageSize);
                params.put("offset", pageSize * pageNumber);
            }

            Integer loginType = token.getLoginType();
            String userId = token.getId();
            String enterpriseUserId = token.getEnterpriseUserId();

            if (loginType == 1) {
                // if (communityList != null && !communityList.isEmpty()) {
                //    StringBuilder communityIds = new StringBuilder("");
                //    for (Map<String, Object> map : communityList) {
                //        communityIds.append("'" + map.get("communityId") + "'").append(",");
                //    }
                //    String communityIdsStr = communityIds.toString().substring(0, communityIds.toString().lastIndexOf(","));
                //
                //    querySql += "  AND sc.id IN (  " + communityIdsStr + " )  ";
                //    countSql += "  AND sc.id IN (  " + communityIdsStr + " )  ";
                //} else {
                //    querySql += "  AND sc.id IN ( null )  ";
                //    countSql += "  AND sc.id IN ( null )  ";
                //}
                // 修复只查询出对应机构下的房产 20230306 xiaolong
                if (enterpriseId != null) {
                    DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
                    // 查询出企业的标签
                    enterpriseId = hierarchy.getId();
                    List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(enterpriseId);
                    List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());// 用户企业标签
                    // 判断是否是政府机构
                    if (enterpriseTagIds.contains(3L)) {
                        querySql += " ( 1 = 1 AND sch.status = 1 ";
                        countSql += " ( 1 = 1 AND sch.status = 1 ";
                    } else {
                        querySql += " 1 = 1 AND sch.status = 1 ";
                        countSql += " 1 = 1 AND sch.status = 1 ";
                    }
                    // 判断机构是否带有单位承租人标签
                    Long unitLesseeId = null;
                    unitLesseeId = hierarchy.getOrgId();
                    params.put("unitLesseeId", unitLesseeId);

                    Long orgId = null;
                    orgId = hierarchy.getOrgId();
                    params.put("orgId", orgId);

                    // 3、物业，查已绑定该物业的小区下的所有房产
                    Long housePropertyId = null;
                    housePropertyId = hierarchy.getOrgId();
                    params.put("housePropertyId", housePropertyId);
                    querySql += " and (sch.house_property_id = :housePropertyId OR sch.org_id = :orgId OR sch.unit_lessee_id = :unitLesseeId ) ";
                    countSql += " and (sch.house_property_id = :housePropertyId OR sch.org_id = :orgId OR sch.unit_lessee_id = :unitLesseeId )";
                    // 1、政府机构，根据区域标签所对应区域id查
                    Long areaTagId = hierarchy.getTagId();// 区域标签
                    Long areaId = null;
                    if (enterpriseTagIds.contains(3L)) {
                        areaId = hierarchy.getAreaId();// 区域id
                        String areaTag = "province_id";
                        if (areaTagId == 1) {
                            areaTag = "province_id";
                            params.put("areaId", areaId);
                            querySql += " OR sch.province_id = :areaId )";
                            countSql += " OR sch.province_id = :areaId )";
                        } else if (areaTagId == 2) {
                            areaTag = "city_id";
                            params.put("areaId", areaId);
                            querySql += " OR sch.city_id = :areaId )";
                            countSql += " OR sch.city_id = :areaId )";
                        } else if (areaTagId == 3) {
                            areaTag = "district_id";
                            params.put("areaId", areaId);
                            querySql += " OR sch.district_id = :areaId )";
                            countSql += " OR sch.district_id = :areaId )";
                        } else if (areaTagId == 4) {
                            areaTag = "street_id";
                            params.put("areaId", areaId);
                            querySql += " OR sch.street_id = :areaId )";
                            countSql += " OR sch.street_id = :areaId )";
                        } else if (areaTagId == 5) {
                            areaTag = "community_id";
                            params.put("areaId", areaId);
                            querySql += " OR sch.community_id = :areaId )";
                            countSql += " OR sch.community_id = :areaId )";
                        }
                    }
                }
            } else {
                querySql += " 1 = 1 AND sch.status = 1 ";
                countSql += " 1 = 1 AND sch.status = 1 ";
                List<String> houseIdList = communityService.getHouseIdList(userId);
                if (houseIdList.isEmpty()) {
                    apiData.setTotal(0L);
                    apiData.setData(new ArrayList<>());
                    return ResultBean.successfulResult(apiData);
                }

                StringBuilder houseIds = new StringBuilder("");
                for (String hId : houseIdList) {
                    houseIds.append("'" + hId + "'").append(",");
                }
                String houseIdsStr = houseIds.toString().substring(0, houseIds.toString().lastIndexOf(","));
                querySql += "  AND sch.id IN (  " + houseIdsStr + " )  ";
                countSql += "  AND sch.id IN (  " + houseIdsStr + " )  ";
            }


            // 房屋id，小区名称，房号，产权人名
            if (!StringUtils.isEmpty(searchCondition)) {
                params.put("searchCondition", "%" + searchCondition + "%");
                querySql += " AND (sch.id LIKE :searchCondition OR sc.name LIKE :searchCondition OR sch.room_number LIKE :searchCondition OR (sch.owner_name like :searchCondition or d.name like :searchCondition) OR sch.owner_mobile like :searchCondition) ";
                countSql += " AND (sch.id LIKE :searchCondition OR sc.name LIKE :searchCondition OR sch.room_number LIKE :searchCondition OR (sch.owner_name like :searchCondition or d.name like :searchCondition) OR sch.owner_mobile like :searchCondition) ";
            }

            if (!StringUtils.isEmpty(houseId)) {
                params.put("houseId", houseId);
                querySql += " AND sch.id = :houseId ";
                countSql += " AND sch.id = :houseId ";
            }

            if (!StringUtils.isEmpty(communityId)) {
                params.put("communityId", communityId);
                querySql += " AND sch.residence_community_id = :communityId ";
                countSql += " AND sch.residence_community_id = :communityId ";
            }

            if (buildId != null) {
                params.put("buildId", buildId);
                querySql += " AND sch.building_num = :buildId ";
                countSql += " AND sch.building_num = :buildId ";
            }

            if (unitId != null) {
                params.put("unitId", unitId);
                querySql += " AND sch.unit = :unitId ";
                countSql += " AND sch.unit = :unitId ";
            }

            if (!StringUtils.isEmpty(roomNumber)) {
                params.put("roomNumber", roomNumber);
                querySql += " AND sch.room_number = :roomNumber ";
                countSql += " AND sch.room_number = :roomNumber ";
            }

            if (floor != null) {
                params.put("floor", floor);
                querySql += " AND sch.floor = :floor ";
                countSql += " AND sch.floor = :floor ";
            }

            if (!StringUtils.isEmpty(ownerName)) {
                params.put("ownerName", ownerName);
                querySql += " AND (sch.owner_name like :ownerName or d.name like :ownerName)";
                countSql += " AND (sch.owner_name like :ownerName or d.name like :ownerName)";
            }

            if (!StringUtils.isEmpty(ownerMobile)) {
                params.put("ownerMobile", ownerMobile);
                querySql += " AND sch.owner_mobile = :ownerMobile ";
                countSql += " AND sch.owner_mobile = :ownerMobile ";
            }

            if (userCount != null) {
                if (userCount == 0) {
                    // 修复成员人数搜索0，显示有成员的房产，查询出了合租的房产 xiaolong 20230329
                    // querySql += " AND pp.userCount is null ";
                    // countSql += " AND pp.userCount is null ";
                    querySql += " AND pp.userCount is null AND sch.match_type = 1";
                    countSql += " AND pp.userCount is null AND sch.match_type = 1";
                } else {
                    params.put("userCount", userCount);
                    querySql += " AND pp.userCount = :userCount ";
                    countSql += " AND pp.userCount = :userCount ";
                }
            }
            List<Object> args = new ArrayList<>();

            // querySql += " order by sch.create_time desc ";
            querySql += " ORDER BY sc.name,scb.name,scbu.name,sch.room_number ASC ";
            if (determineType != null && determineType == 1) {
                querySql += " LIMIT :limit OFFSET :offset ";
            }

            List<PropertyCommunityHouseVO> communityHouseList = namedParameterJdbcTemplate.query(querySql, params,
                    new BeanPropertyRowMapper<>(PropertyCommunityHouseVO.class));
            // 新增查询用户入住时间
            // List<CommunityHouseUser> byUserId = communityHouseUserRepository.findByUserIdAndStatus(userId,1);
            List<CommunityHouseUser> byUserId = communityHouseUserRepository.findByMobileAndStatus(phone, 1);
            int i = 0;
            for (PropertyCommunityHouseVO propertyCommunityHouseVO : communityHouseList) {
                // 新增入住时间（天）
                for (CommunityHouseUser communityHouseUser : byUserId) {
                    String communityHouseId = communityHouseUser.getCommunityHouseId();
                    String id = propertyCommunityHouseVO.getId();
                    if (communityHouseId.equals(id)) {
                        Date operatorTime = communityHouseUser.getOperatorTime();
                        Date date = new Date();// 当前时间
                        long time = operatorTime.getTime();// 入住时间
                        long dateTime = date.getTime();
                        long num = dateTime - time;
                        num = num / 24 / 60 / 60 / 1000 + 1;
                        propertyCommunityHouseVO.setIntakeNum(num);
                    }

                }
            }
            Long count = namedParameterJdbcTemplate.queryForObject(countSql, params, Long.class);
            // 获取房产id列表
            List<String> communityHouseIds = communityHouseList.stream().filter(h -> h.getHouseNature() != 1).map(h -> h.getId()).collect(Collectors.toList());
            // 查询房产租户信息
            updateHouseUserInfo(communityHouseIds, communityHouseList);

            // 查询公租房id
            List<String> houseIds = communityHouseList.stream().filter(h -> h.getHouseNature() == 1).map(h -> h.getId()).collect(Collectors.toList());
            // 查询公租房租户信息
            updateHouseUserInfo2(houseIds, communityHouseList);

            // 公租房查询产权单位名称
            List<Long> orgIds = communityHouseList.stream().filter(PropertyCommunityHouseVO -> PropertyCommunityHouseVO.getOrgId() != null).map(PropertyCommunityHouseVO::getOrgId).distinct().collect(Collectors.toList());
            if (!orgIds.isEmpty()) {
                Map<Long, String> map = departmentRepository.findByIdIn(orgIds).stream().collect(Collectors.toMap(Department::getId, Department::getName));
                if (!map.isEmpty()) {
                    communityHouseList.forEach(vo -> {
                        if (vo.getHouseNature() == 1) {
                            vo.setOwnerName(map.get(vo.getOrgId()));
                        }
                    });
                }
            }

            if (communityHouseList != null && !communityHouseList.isEmpty()) {
                // 新增部分

                args = communityHouseList.stream().map(c -> c.getId()).collect(Collectors.toList());
                String queryIsLessee = "SELECT muh.match_user_stock_id AS matchUserId,sh.id AS houseId FROM saas_house sh\n" +
                        "LEFT JOIN m_match_user_house muh\n" +
                        "ON muh.house_id = sh.id\n" +
                        "LEFT JOIN m_match_user_stock mus\n" +
                        "ON muh.match_user_stock_id = mus.id\n" +
                        " WHERE sh.id in " + SqlUtils.foreachIn(args.size());
                List<MatchUserVO> query = jdbcTemplate.query(queryIsLessee, new BeanPropertyRowMapper<>(MatchUserVO.class), args.toArray());
                for (PropertyCommunityHouseVO propertyCommunityHouseVO : communityHouseList) {
                    // 新增同住人数
                    Integer userCount1 = propertyCommunityHouseVO.getUserCount();
                    if (userCount1 != null) {
                        if (userCount1 >= 0) {
                            Integer inmateCount = userCount1 - 1;
                            propertyCommunityHouseVO.setInmateCount(inmateCount);
                        }
                    }
                    if (query != null && !query.isEmpty()) {
                        for (MatchUserVO matchUserVO : query) {
                            if (matchUserVO.getHouseId().equals(propertyCommunityHouseVO.getId())) {
                                if (StringUtils.isNotBlank(matchUserVO.getMatchUserId())) {
                                    propertyCommunityHouseVO.setIsLessee(1);
                                } else {
                                    propertyCommunityHouseVO.setIsLessee(0);
                                }
                            }
                        }
                    } else {
                        propertyCommunityHouseVO.setIsLessee(0);
                    }
                }
                String labelQuery = " SELECT schu.community_house_id,schu.change_label FROM saas_community_house_user schu WHERE schu.community_house_id in " + SqlUtils.foreachIn(args.size());

                List<CommunityHouseUserVO> query1 = jdbcTemplate.query(labelQuery, new BeanPropertyRowMapper<>(CommunityHouseUserVO.class), args.toArray());
                for (PropertyCommunityHouseVO propertyCommunityHouseVO : communityHouseList) {
                    if (query1 != null && !query1.isEmpty()) {
                        for (CommunityHouseUserVO communityHouseUserVO : query1) {
                            if (communityHouseUserVO.getCommunityHouseId().equals(propertyCommunityHouseVO.getId())) {
                                if (communityHouseUserVO.getChangeLabel() == null) {
                                    propertyCommunityHouseVO.setChangeLabel(0);
                                }
                                if (communityHouseUserVO.getChangeLabel() != null && communityHouseUserVO.getChangeLabel() == 1) {
                                    propertyCommunityHouseVO.setChangeLabel(1);
                                } else {
                                    propertyCommunityHouseVO.setChangeLabel(0);
                                }
                            } else {
                                propertyCommunityHouseVO.setChangeLabel(0);
                            }
                        }
                    } else {
                        propertyCommunityHouseVO.setChangeLabel(0);
                    }
                }
            }

            // 新增合租房产的成员人数
            for (PropertyCommunityHouseVO propertyCommunityHouseVO : communityHouseList) {
                String id = propertyCommunityHouseVO.getId();
                String housemateId = propertyCommunityHouseVO.getHousemateId();
                // 配租方式：1整租  2合租
                Integer matchType = propertyCommunityHouseVO.getMatchType();
                // 如果没有合租子房产id，就说明是合租房产
                if (housemateId == null && matchType != null && matchType == 2) {
                    Integer num = 0;
                    // 查询出所有合租房产下的子房产
                    List<House> byHousemateIdAndStatus = houseRepository.findByHousemateIdAndStatus(id, 1);
                    for (House housemateIdAndStatus : byHousemateIdAndStatus) {
                        String id1 = housemateIdAndStatus.getId();
                        List<CommunityHouseUser> byCommunityHouseIdAndStatus = communityHouseUserRepository.findByCommunityHouseIdAndStatus(id1, 1);
                        num += byCommunityHouseIdAndStatus.size();
                    }
                    propertyCommunityHouseVO.setUserCount(num);
                }
            }

            // 增加智能锁id和智能锁授权用户id
            for (PropertyCommunityHouseVO communityHouseVO : communityHouseList) {
                String id2 = communityHouseVO.getId();
                if (StrUtil.isNotEmpty(communityHouseVO.getHousemateId())) {
                    id2 = communityHouseVO.getHousemateId();
                }
                SmartLockAuth byHouseIdAndMobile = smartLockAuthRepository.findByHouseIdAndMobile(id2, phone);
                // 不同房屋对应不同智能锁
                if (byHouseIdAndMobile != null) {
                    String houseId1 = byHouseIdAndMobile.getHouseId();
                    Long id = byHouseIdAndMobile.getId();
                    Long lockId = byHouseIdAndMobile.getLockId();
                    for (PropertyCommunityHouseVO propertyCommunityHouseVO : communityHouseList) {
                        String id1 = propertyCommunityHouseVO.getId();
                        if (houseId1.equals(id1) || houseId1.equals(propertyCommunityHouseVO.getHousemateId())) {
                            propertyCommunityHouseVO.setLockAuthId(id);
                            propertyCommunityHouseVO.setLockId(lockId);
                        }

                    }

                }
            }
            // 新增合租房子的智能锁id和智能锁授权用户id
            // for (PropertyCommunityHouseVO propertyCommunityHouseVO : communityHouseList) {
            //     String housemateId = propertyCommunityHouseVO.getHousemateId();
            //     if (housemateId != null) {
            //         List<SmartLock> byHouseId = smartLockRepository.findByHouseId(housemateId);
            //         if (!byHouseId.isEmpty()) {
            //             Long lockId = byHouseId.get(0).getId();
            //             propertyCommunityHouseVO.setLockId(lockId);
            //             List<SmartLockAuth> byLockId = smartLockAuthRepository.findByLockId(lockId);
            //             if (!byLockId.isEmpty()) {
            //                 Long lockAuthId = byLockId.get(0).getId();
            //                 propertyCommunityHouseVO.setLockAuthId(lockAuthId);
            //             }
            //         }
            //     }
            // }
            List<String> houseIdList = communityHouseList.stream().map(PropertyCommunityHouseVO::getId).collect(Collectors.toList());
            List<CommunityHouseUser> communityHouseUserList = communityHouseUserRepository.findByCommunityHouseIdInAndStatus(houseIdList, 1);
            Map<String, List<CommunityHouseUser>> collect = communityHouseUserList.stream().collect(Collectors.groupingBy(CommunityHouseUser::getCommunityHouseId));
            for (PropertyCommunityHouseVO propertyCommunityHouseVO : communityHouseList) {
                String id = propertyCommunityHouseVO.getId();
                String housemateId = propertyCommunityHouseVO.getHousemateId();
                // 锁是绑定在父房间的，所以是子房间，得换成父房间的id
                if (StrUtil.isNotBlank(housemateId)) {
                    id = housemateId;
                }
                String lockType = smartLockRepository.lockType(id);
                if (!StringUtils.isEmpty(lockType)) {
                    propertyCommunityHouseVO.setLockType(lockType);
                }


                List<CommunityHouseUser> communityHouseUsers = collect.get(propertyCommunityHouseVO.getId());
                if (CollectionUtil.isNotEmpty(communityHouseUsers)) {
                    boolean openPushMessageType = communityHouseUsers.stream()
                            .anyMatch(person -> "1".equals(person.getOpenPushMessageType()));
                    if (openPushMessageType) {
                        propertyCommunityHouseVO.setOpenPushMessageType("1");
                    } else {
                        propertyCommunityHouseVO.setOpenPushMessageType("0");
                    }
                } else {
                    propertyCommunityHouseVO.setOpenPushMessageType("0");
                }

                String queryIsLessee = "SELECT muh.* ,muus.phone as phone FROM m_match_user_house muh left join m_match_user_stock  muus on muus.id = muh.match_user_stock_id WHERE muh.house_id = ? ";
                List<MatchUserHouseVO> query = jdbcTemplate.query(queryIsLessee, new BeanPropertyRowMapper<>(MatchUserHouseVO.class), propertyCommunityHouseVO.getId());
                if (CollectionUtil.isNotEmpty(query)) {
                    MatchUserHouseVO matchUserHouseVO = query.get(0);
                    ElectronicSigningContract electronicSigningContract = new ElectronicSigningContract();
                    electronicSigningContract.setContractStartTime(matchUserHouseVO.getStartDate());
                    electronicSigningContract.setContractEndTime(matchUserHouseVO.getEndDate());
                    electronicSigningContract.setHouseId(matchUserHouseVO.getHouseId());
                    electronicSigningContract.setUserPhone(matchUserHouseVO.getPhone());

                    boolean b = electronicSigningContractService.checkContractExist(electronicSigningContract);
                    if (b) {
                        propertyCommunityHouseVO.setContractStatus(1);
                    } else {
                        propertyCommunityHouseVO.setContractStatus(0);
                    }
                }
            }
            apiData.setTotal(count);
            apiData.setData(communityHouseList);
            return ResultBean.successfulResult(apiData);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> changeOwner(String accessToken, String houseId, String ownerName, String ownerMobile, Integer orgId, Integer ownerType) {
        TokenRedisVo token = redisService.findTokenVo(accessToken);
        if (token == null)
            return ResultBean.failedResultOfToken();

        String updateSql = "UPDATE saas_house SET owner_name = ?, owner_mobile = ?, org_id = ?,owner_type = ? WHERE id = ?";
        int result = jdbcTemplate.update(updateSql, ownerName, ownerMobile, orgId, ownerType, houseId);

        // 更新智能锁产权人名称
        List<SmartLock> smartLocks = smartLockRepository.findByHouseId(houseId);
        if (!smartLocks.isEmpty()) {
            SmartLock smartLock = smartLocks.get(0);
            smartLock.setOrgName(ownerName);
            smartLockRepository.save(smartLock);
        }

        return result == 1 ? ResultBean.successfulResult(null)
                : ResultBean.failedResultWithStatus(StatusCode.ERROR_CODE_10001);
    }

    /**
     * 查询租户信息
     *
     * @param houseIds
     * @param communityHouseList
     * @author shun
     * @date 2021年6月2日
     */
    public void updateHouseUserInfo(List<String> houseIds, List<PropertyCommunityHouseVO> communityHouseList) {
        if (houseIds == null || houseIds.size() <= 0) {
            return;
        }
        String sql = "SELECT u.id,u.name,u.mobile,u.type,u.community_house_id FROM saas_community_house_user u WHERE u.status = 1 AND u.community_house_id in "
                + SQLUtils.foreachIn(houseIds.size()) + " ORDER BY u.id";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, houseIds.toArray());
        if (!list.isEmpty()) {
            Map<String, List<HouseUserVo>> userMap = new HashMap<>();

            for (Map<String, Object> map : list) {
                String communityhouseId = String.valueOf(map.get("community_house_id"));
                List<HouseUserVo> userList = userMap.get(communityhouseId);
                if (userList == null) {
                    userList = new ArrayList<HouseUserVo>();
                }
                HouseUserVo userVo = new HouseUserVo();
                userVo.setMobile(String.valueOf(map.get("mobile")));
                userVo.setUserName(String.valueOf(map.get("name")));
                userVo.setType(Integer.parseInt(String.valueOf(map.get("type"))));
                userList.add(userVo);
                userMap.put(communityhouseId, userList);
            }

            for (Map.Entry<String, List<HouseUserVo>> map : userMap.entrySet()) {
                HouseUserVo userVo = null;
                // 只返回租客信息
                for (HouseUserVo vo : map.getValue()) {
                    if (vo.getType() == 1) {
                        userVo = vo;
                        break;
                    }
                }

                for (PropertyCommunityHouseVO hvo : communityHouseList) {
                    if (hvo.getHouseNature() != 1 && hvo.getId().equals(map.getKey())) {
                        hvo.setTenantName(userVo == null ? "" : userVo.getUserName());
                        hvo.setTenantMobile(userVo == null ? "" : userVo.getMobile());
                        // hvo.setUserCount(map.getValue().size());
                    }
                }
            }
        }
    }

    public void updateHouseUserInfo2(List<String> houseIds, List<PropertyCommunityHouseVO> communityHouseList) {
        if (houseIds == null || houseIds.size() <= 0) {
            return;
        }

        String sql = "SELECT m.house_id as houseId,u.name AS name1,u2.name AS name2,u.phone as phone1,u2.phone as phone2 \n" +
                "FROM saas_house_match_user m \n" +
                "LEFT JOIN `saas_app_user` u ON m.match_user_id = u.id\n" +
                "LEFT JOIN `saas_app_user` u2 ON m.match_user_id = u2.enterprise_user_id  \n" +
                "WHERE m.status = 1 and m.house_id in " + SqlUtils.foreachIn(houseIds.size());
        List<MatchUserVO> matchUsers = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(MatchUserVO.class), houseIds.toArray());
        if (!matchUsers.isEmpty()) {
            for (PropertyCommunityHouseVO vo : communityHouseList) {
                List list = new ArrayList<>();
                for (MatchUserVO matchUser : matchUsers) {
                    if (vo.getId().equals(matchUser.getHouseId())) {
                        String name = "";
                        String mobile = "";
                        String name1 = matchUser.getName1();
                        String name2 = matchUser.getName2();
                        String phone1 = matchUser.getPhone1();
                        String phone2 = matchUser.getPhone2();
                        if (StringUtils.isNotBlank(name1)) {
                            name = name1;
                            mobile = phone1;
                        }
                        if (StringUtils.isNotBlank(name2)) {
                            name = name2;
                            mobile = phone2;
                        }
                        Map<String, Object> map = new HashMap<>();
                        map.put("tenantName", name);
                        map.put("tenantMobile", mobile);
                        list.add(map);
                    }
                }
                vo.setMatchUser(list);
            }
        }

        /*String sql2 = "SELECT h.id,pp.userNumber FROM saas_house h\n" +
                "LEFT JOIN (\n" +
                "SELECT houseId, SUM(userNumber) AS userNumber FROM (\n" +
                "SELECT h.id AS houseId, COUNT(app.match_user_id) userNumber \n" +
                "FROM saas_house_eligible_apply app\n" +
                "LEFT JOIN saas_house_match_user mu ON  mu.apply_id = app.id\n" +
                "LEFT JOIN saas_house h ON h.id = mu.house_id  WHERE h.id IN " + SqlUtils.foreachIn(houseIds.size()) + " GROUP BY h.id \n" +
                "UNION ALL\n" +
                "SELECT h.id AS houseId, COUNT(ac.id) AS userNumber \n" +
                "FROM saas_house_eligible_apply_cohabit ac\n" +
                "LEFT JOIN saas_house_eligible_apply app ON app.id = ac.apply_id\n" +
                "LEFT JOIN saas_house_match_user mu ON  mu.apply_id = app.id\n" +
                "LEFT JOIN saas_house h ON h.id = mu.house_id  WHERE h.id IN " + SqlUtils.foreachIn(houseIds.size()) + " GROUP BY h.id \n" +
                ") p GROUP BY houseId \n" +
                ") pp \n" +
                "ON pp.houseId = h.id";
        List<Object> args = new ArrayList<>();
        args.addAll(houseIds);
        args.addAll(houseIds);
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql2, args.toArray());
        if (!list.isEmpty()) {
            for (Map<String, Object> map : list) {
                String houseId = map.get("id").toString();
                Integer userNumber = Integer.valueOf(map.get("userNumber") == null ? "0" : map.get("userNumber").toString());
                for (PropertyCommunityHouseVO vo : communityHouseList) {
                    if (vo.getHouseNature() == 1 && vo.getId().equals(houseId)) {
                        vo.setUserCount(userNumber);
                    }
                }
            }
        }*/
    }


}
